package admin_service

import (
	"shop/dao"
	"shop/entity"
	"shop/utils/convertutil"
	"shop/utils/result"
)

func GetRoleList() *result.Result {
	list := make([]*entity.SysRole, 0, 0)
	dao.GetDB().Table(entity.TableNameSysRole).Find(&list)
	for _, role := range list {
		role.PermissionList = make([]string, 0, 0)
		convertutil.ParseJson(role.Permissions, &role.PermissionList)
	}
	return result.Ok(list)
}

func AddRole(role *entity.SysRole) *result.Result {
	rows := dao.GetTx().Model(role).Create(role).Commit().RowsAffected
	return result.Ok(rows)
}

func UpdateRole(roleId int, role *entity.SysRoleFilter) *result.Result {
	if role.PermissionList != nil && len(role.PermissionList) > 0 {
		role.Permissions = convertutil.ToJsonString(role.PermissionList)
	}
	rows := dao.GetTx().Model(role).Where("id", roleId).Updates(role).Commit().RowsAffected
	return result.Ok(rows)
}

func DeleteRole(id int) *result.Result {
	rows := dao.GetTx().Table(entity.TableNameSysRole).Where("id", id).Delete(nil).Commit().RowsAffected
	return result.Ok(rows)
}
